package cn.itcast.fore.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.ws.rs.core.MediaType;

import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.take_delivery.PageBean;
import cn.itcast.bos.domain.take_delivery.Promotion;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class PromotionAction extends BaseAction<Promotion> {

	@Action(value = "promotion_querypage", results = { @Result(name = "success", type = "json") })
	public String queryPage() {

		PageBean pageBean = WebClient
				.create("http://localhost:8080/bos_management/services/promotionService/queryPromotion?page="
						+ page + "&rows=" + rows)
				.accept(MediaType.APPLICATION_JSON).get(PageBean.class);

		ServletActionContext.getContext().getValueStack().push(pageBean);

		return SUCCESS;
	}

	@Action(value = "promotion_showDetail")
	public String showDetail() throws Exception{

		String path = ServletActionContext.getServletContext().getRealPath(
				"/freemarker");
		File file = new File(path + "/" + model.getId() + ".html");
		if (!file.exists()) {

			Configuration configuration = new Configuration(
					Configuration.VERSION_2_3_0);

			configuration
					.setDirectoryForTemplateLoading(new File(ServletActionContext.getServletContext().getRealPath("/WEB-INF/promotion_template")));
			
			Template template = configuration
					.getTemplate("promotion_detail.ftl");
			Promotion promotion = WebClient
					.create("http://localhost:8080/bos_management/services/promotionService/queryPromotionById?id="
							+ model.getId()).accept(MediaType.APPLICATION_JSON)
					.get(Promotion.class);
			HashMap<String,Object> hashMap = new HashMap<String, Object>();
			hashMap.put("promotion", promotion);

			template.process(hashMap, new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
			
		}
		ServletActionContext.getResponse().setContentType("text/html:charset=utf-8");
		
		FileUtils.copyFile(file, ServletActionContext.getResponse().getOutputStream());

		return NONE;
	}

}
